/*
 *  Copyright 2011 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.vcforms.template.archive;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.opu.vcforms.template.bean.docx.MetaInf;

/**
 *
 * @author yura
 */
public class DocxArchiveTemplate extends AbstractArchiveTemplate {
    public static final String META_INF_NAME = "META-INF.xml";
    public static final String DOCX_TEMPLATE_NAME = "template.docx";

    private Map<String, byte[]> docxFile = new HashMap<String, byte[]>();
    private MetaInf metaInf = new MetaInf();

    public Map<String, byte[]> getDocxFile() {
        return docxFile;
    }

    public void setDocxFile(Map<String, byte[]> docxFile) {
        this.docxFile = docxFile;
    }

    public MetaInf getMetaInf() {
        return metaInf;
    }

    public void setMetaInf(MetaInf metaInf) {
        this.metaInf = metaInf;
    }

    @Override
    public void onLoad(String name, byte[] data) throws IOException {
        if(META_INF_NAME.equals(name)){
            if (metaInf == null){
                metaInf = new MetaInf();
            }

            metaInf.load(new ByteArrayInputStream(data));
        } else if(DOCX_TEMPLATE_NAME.equals(name)){
            docxFile = archiveUtil.readArchive(new ByteArrayInputStream(data));
        }
    }

    @Override
    public byte[] onStore(String name, byte[] data) throws IOException {
        if(META_INF_NAME.equals(name)){
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            metaInf.store(bout);
            return bout.toByteArray();
        } else if(DOCX_TEMPLATE_NAME.equals(name)){
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            archiveUtil.writeArchive(docxFile, bout);
            return bout.toByteArray();
        } else{
            return super.onStore(name, data);
        }
    }

    @Override
    public String[] requred() {
        return new String[]{META_INF_NAME, DOCX_TEMPLATE_NAME};
    }

}
